package com.itheima.aop;

import com.alibaba.fastjson.JSON;
import com.itheima.pojo.OperateLog;
import com.itheima.pojo.Result;
import com.itheima.service.OperateLogService;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Arrays;

@Slf4j
@Component
@Aspect
public class OperateLogAspect {
    //操作日志切面 记录操作日志

    //获取请求
    @Autowired
    private HttpServletRequest request;

    @Autowired
    private OperateLogService operateLogService;

    //环绕通知
    @Around("@annotation(com.itheima.anno.Log)")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        //获取操作用户id
        String jwt = request.getHeader("token");
        Claims claims = JwtUtils.parseToken(jwt);
        int operationUserId = (int) claims.get("id");
        //获取类名
        String className = joinPoint.getTarget().getClass().getName();

        //获取方法名
        String methodName = joinPoint.getSignature().getName();

        //获取参数列表
        Object[] args = joinPoint.getArgs();


        long start = System.currentTimeMillis();

        //获取返回值
        Object result = joinPoint.proceed();//执行目标方法
        log.info("执行方法{}，返回值{}", methodName, result);
        //获取方法执行耗时
        long end = System.currentTimeMillis();
        long time = end - start;

        OperateLog operateLog = new OperateLog();
        operateLog.setClassName(className);
        operateLog.setMethodName(methodName);
        operateLog.setMethodParams(Arrays.toString(args));
        operateLog.setReturnValue(JSON.toJSONString(result));
        operateLog.setOperateUserId(operationUserId);
        operateLog.setCostTime(time);
        operateLog.setOperateTime(LocalDateTime.now());

        //保存操作日志
        operateLogService.insert(operateLog);

        return result;
    }


}
